package main

import (
	"bufio"
	"encoding/json"
	"gitee.com/DonHz/cloud-file-storage/config"
	"gitee.com/DonHz/cloud-file-storage/db"
	"gitee.com/DonHz/cloud-file-storage/mq"
	"gitee.com/DonHz/cloud-file-storage/store/oss"
	"log"
	"os"
)

func ProcessTransfer(msg []byte) bool {
	// 1.解析msg
	var pubData mq.TransferData
	err := json.Unmarshal(msg, &pubData)
	if err != nil {
		log.Println(err)
		return false
	}
	// 2.根据临时存储文件的路径，创建文件句柄，
	f, err := os.Open(pubData.CurLocation)
	if err != nil {
		log.Println(err)
		return false
	}
	// 3.通过文件句柄将文件内容读出来，通过oss接口将文件上传到oss
	err = oss.Bucket().PutObject(pubData.DestLocation, bufio.NewReader(f))
	if err != nil {
		log.Println(err)
		return false
	}
	// 4.更新文件的存储路径到文件表mysql中
	IsSuccess := db.UpdateFileLocation(pubData.FileHash, pubData.DestLocation)
	if !IsSuccess {
		return false
	}
	return true
}

func main() {
	log.Println("开始监听转移任务队列...")
	mq.StartConsume(
		config.TransOSSQueueName,
		"transfer_oss",
		ProcessTransfer,
	)
}
